import CodoBase from "../../../lib/CodoBase";
import CodoError from "../../../lib/CodoError";
import { Wechat } from "../wechat";

export default class CodoWechatMPUserInfo extends CodoBase {
	/**
	 * 根据小程序前端获取到的获取手机号code来获取手机号，前端按钮是收费的
	 * - https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
	 */
	async getPhoneNumber(code: string, access_token?: string) {
		const token = access_token || this.app.codo.wechat.mp.accessToken.getCurrentContextCacheAccessToken();
		const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${token}`;
		const res = await this.app.curl<Wechat.mp.response.GetPHoneNumber>(url, {
			method: "POST",
			contentType: "json",
			dataType: "json",
			data: {
				code,
			},
		});
		if (res.data.errcode) {
			throw new CodoError(`mp获取手机号错误，errcode %s，errmsg %s`, res.data.errcode, res.data.errmsg);
		}
        return res.data;
	}
}
